package com.gosdk.p;

import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;

import com.gosdk.p.vo.Offer;
import com.gosdk.p.vo.OfferConfigManager;

public class BushManager {
	public static boolean isRunning = false;
	public static Notification n;

	/**
	 * 1. 首先判断是否有正在展示的广告，如果有广告，则替换成新的offer 2. 没有广告则直接展示
	 * 
	 * @param context
	 * @param offers
	 */
	public static void pushAction(Context context, List<Offer> offers) {

		if (OfferConfigManager.isAdClosed(context)) {
			return;
		}
		
		List<PackageInfo> packageList = context.getPackageManager().getInstalledPackages(0);
		Offer selectedOffer = null;
		for (Offer item : offers) {
			if (AppManager.isAppInstalled(context, item.getPackagename(), packageList)) {
				continue;
			} else {
				// 选出第一个没有安装的app
				selectedOffer = item;
			}
		}
		
		if (selectedOffer == null) {
			return;
		}
		
		NotificationManager nm = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		n = new Notification(android.R.drawable.ic_menu_search,
				"Hello,there!", System.currentTimeMillis());
		n.flags = Notification.FLAG_NO_CLEAR;
		Intent i = new Intent(context, AdClickService.class);
		Bundle mBundle = new Bundle();  
        mBundle.putSerializable("offer", selectedOffer);  
        i.putExtras(mBundle);  
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getService(context,
				R.string.app_name, i, PendingIntent.FLAG_CANCEL_CURRENT);

		n.setLatestEventInfo(context, selectedOffer.getName(), selectedOffer.getContent(),
				contentIntent);
		nm.notify(R.string.app_name, n);
	}
}
